package com.freely.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.freely.FR;
import com.freely.R;
import com.freely.R2;
import com.freely.component.activity.NavigationActivity;
import com.freely.data.network.ServerException;
import com.freely.data.network.requestEntities.RQDeviceCode;
import com.freely.data.network.requestEntities.RQUserRegister;
import com.freely.data.network.requestEntities.RQVerificationCheck;
import com.freely.ui.util.DataVerification;
import com.freely.ui.util.VerificationUtil;
import com.freely.ui.viewModel.RegisterViewModel;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.util.Objects;

import androidx.appcompat.widget.AppCompatButton;
import androidx.lifecycle.ViewModelProviders;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

public class RegisterActivity extends NavigationActivity {
    private static final String TAG = "RegisterActivity";
    private RegisterViewModel viewModel;

    @BindView(R2.id.user_head_icon)
    ImageView headIcon;
    @BindView(R2.id.input_user_name_layout)
    TextInputLayout userNameLayout;
    @BindView(R2.id.input_user_name)
    TextInputEditText userName;
    @BindView(R2.id.input_user_password_layout)
    TextInputLayout userPasswordLayout;
    @BindView(R2.id.input_user_password)
    TextInputEditText userPassword;
    @BindView(R2.id.input_user_email_layout)
    TextInputLayout userEmailLayout;
    @BindView(R2.id.input_user_email)
    TextInputEditText userEmail;
    @BindView(R2.id.input_verification_code_layout)
    TextInputLayout verificationCodeLayout;
    @BindView(R2.id.input_verification_code)
    TextInputEditText verificationCode;
    @BindView(R2.id.verification_code_image)
    ImageView verificationCodeImage;
    @BindView(R2.id.register_button)
    AppCompatButton registerButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        viewModel = ViewModelProviders.of(this).get(RegisterViewModel.class);
        init();
    }

    //activity 初始化
    void init() {
        //得到验证码回调
        viewModel.getVerificationCodeImage().observe(this, single -> single.subscribe(bytes -> {
            //验证码请求成功
            Glide.with(RegisterActivity.this)
                    .asBitmap()
                    .load(bytes)
                    .into(verificationCodeImage);
        }, throwable -> {
            Log.d(TAG, "accept: "+throwable.getMessage());
            if (throwable instanceof ServerException) {
                //验证码请求失败
                Toast.makeText(
                        RegisterActivity.this,
                        throwable.getMessage(),
                        Toast.LENGTH_SHORT
                ).show();
            }
        }).dispose());

        //验证验证码结果回调
        viewModel.getVerificationCodeCheckResult().observe(this, single -> single.subscribe(aBoolean -> {
            //验证码正确
            RQUserRegister user = new RQUserRegister(
                    FR.deviceCodeContent,
                    userName.getText().toString(),
                    userPassword.getText().toString(),
                    userEmail.getText().toString()
            );
            viewModel.userRegister(user);
        }, throwable -> {
            //验证码错误
            Log.d(TAG, "accept: "+throwable.getMessage());
            if (throwable instanceof ServerException) {
                Toast.makeText(
                        RegisterActivity.this,
                        throwable.getMessage(),
                        Toast.LENGTH_SHORT
                ).show();
            }
        }).dispose());

        //注册结果回调
        viewModel.getRegisterResult().observe(this, single -> single.subscribe(aBoolean -> {
            //注册成功
            Toast.makeText(
                    RegisterActivity.this,
                    "注册成功，即将返回登陆",
                    Toast.LENGTH_SHORT
            ).show();
            finish();
        }, throwable -> {
            //注册失败
            Log.d(TAG, "accept: "+throwable.getMessage());
            if (throwable instanceof ServerException) {
                Toast.makeText(
                        RegisterActivity.this,
                        throwable.getMessage(),
                        Toast.LENGTH_SHORT
                ).show();
            }
        }).dispose());

        //加载验证码图片
        viewModel.loadVerificationCodeImage(new RQDeviceCode(FR.deviceCodeContent));
    }

    //验证码图片点击监听
    @OnClick(R2.id.verification_code_image)
    void verificationCodeImageOnClick() {
        viewModel.loadVerificationCodeImage(new RQDeviceCode(FR.deviceCodeContent));
    }

    //用户名监听
    @OnTextChanged(R2.id.input_user_name)
    void userNameTextChangedListener(Editable s) {
        VerificationUtil.accountVerificationHint(
                s.toString(),
                userNameLayout,
                getString(R.string.user_account_format_error_hint),
                getString(R.string.user_account_length_error_hint));
    }

    //用户密码监听
    @OnTextChanged(R2.id.input_user_password)
    void userPasswordTextChangedListener(Editable s) {
        VerificationUtil.passwordVerificationHint(
                s.toString(),
                userPasswordLayout,
                getString(R.string.user_password_format_error_hint),
                getString(R.string.user_password_length_error_hint)
        );
    }

    //用户邮箱监听
    @OnTextChanged(R2.id.input_user_email)
    void userEmailTextChangedListener(Editable s) {
        VerificationUtil.emailVerificationHint(
                s.toString(),
                userEmailLayout,
                getString(R.string.user_email_format_error_hint)
        );
    }

    //注册按钮监听
    @OnClick(R2.id.register_button)
    void registerButton() {
        if (registerVerification()) {
            RQVerificationCheck verificationCheck = new RQVerificationCheck(FR.deviceCodeContent, verificationCode
                    .getText().toString());
            viewModel.checkVerificationCode(verificationCheck);
        }
    }

    //注册数据验证
    boolean registerVerification() {
        boolean result = true;
        Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
        //验证验证码
        String verification = verificationCode.getText().toString();
        if (DataVerification.verificationCodeFormatVerification(verification)) {
            verificationCodeLayout.startAnimation(shake);
            verificationCode.setFocusable(true);
            result = false;
        }
        //验证邮箱
        String userEmail = Objects.requireNonNull(
                this.userEmail.getText()
        ).toString();
        if (!DataVerification.userEmailFormatVerification(userEmail)) {
            userEmailLayout.startAnimation(shake);
            this.userEmail.setFocusable(true);
            result = false;
        }
        //验证密码
        String userPassword = Objects.requireNonNull(
                this.userPassword.getText()
        ).toString();
        if (!DataVerification.userPasswordFormatVerification(userPassword)
                || !DataVerification.userPasswordLengthVerification(userPassword)) {
            userPasswordLayout.startAnimation(shake);
            this.userPassword.setFocusable(true);
            result = false;
        }
        //验证用户名
        String userAccount = Objects.requireNonNull(
                this.userName.getText()
        ).toString();
        if (!DataVerification.userAccountFormatVerification(userAccount)
                || !DataVerification.userAccountLengthVerification(userAccount)) {
            userNameLayout.startAnimation(shake);
            this.userName.setFocusable(true);
            result = false;
        }

        return result;
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, RegisterActivity.class);
        context.startActivity(intent);
    }

}
